package com.zhida.chatservice.handler;

import com.zhida.chatservice.service.impl.WebSocketImpl;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

/**
 * Create by zhh 2024/7/8 20:49
 */
public class DefaultWebSocketHandler extends TextWebSocketHandler implements WebSocketHandler {

    @Autowired
    private WebSocketImpl webSocket;

    /**
     * 建立连接
     *
     * @param session Session
     */
    @Override
    public void afterConnectionEstablished(@NonNull WebSocketSession session) {
        webSocket.handleOpen(session);
    }

    /**
     * 接收消息
     *
     * @param session Session
     * @param message 消息
     */
    @Override
    public void handleMessage(@NonNull WebSocketSession session, @NonNull WebSocketMessage<?> message) {
        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            webSocket.handleMessage(session, textMessage.getPayload());
        }
    }

    /**
     * 发生错误
     *
     * @param session   Session
     * @param exception 异常
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) {
        webSocket.handleError(session, exception);
    }

    /**
     * 关闭连接
     *
     * @param session     Session
     * @param closeStatus 关闭状态
     */
    @Override
    public void afterConnectionClosed(@NonNull WebSocketSession session, @NonNull CloseStatus closeStatus) {
        webSocket.handleClose(session);
    }

    /**
     * 是否支持发送部分消息
     *
     * @return false
     */
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    public void sendToUser(String message,String user_session) throws IOException {
        if (webSocket.getSessions()!=null){
            webSocket.sendMessage(message,user_session);
        }
    }

    @Override
    public void handleBinaryMessage(WebSocketSession session,BinaryMessage message){
        webSocket.handleMessage(session,message);
        System.out.println("收到图片");
        byte[] imageBytes = message.getPayload().array();
//        session.sendMessage(new BinaryMessage());
    }
}
